<?php

namespace app\admin\model;

use think\exception\DbException;
use think\Model;
use think\response\Json;


class Organization extends Model
{


    // 表名
    protected $name = 'organization';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'organ_type_text'
    ];
    protected $selectpageFields = "id,organ_name";

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }


    public function getOrganTypeList()
    {
        return ['1' => __('Organ_type 1'), '2' => __('Organ_type 2'), '3' => __('Organ_type 3'), '4' => __('Organ_type 4'),'5' => __('Organ_type 5'),'6' => __('Organ_type 6')];
    }


    public function getOrganTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['organ_type']) ? $data['organ_type'] : '');
        $list = $this->getOrganTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public static function getYard()
    {
        $yardList = self::field('id,organ_name')->order(['weigh' => 'desc', 'createtime', 'id'])->where(['switch' => 1, 'organ_type' => 1])->select();
        return $yardList;
    }

    public function bin()
    {
        return $this->hasMany('app\admin\model\Bin', 'yard_id', 'id', [], 'LEFT')->field('id,bin_sn,yard_id,bin_type,bin_origin,bin_native,current_status');
    }

    public function bcompanybin()
    {
        return $this->hasMany('app\admin\model\Bin', 'bin_company_id', 'id', [], 'LEFT')->field('id,bin_sn,bin_company_id,yard_id,bin_type,bin_origin,bin_native,current_status');
    }
}